package zho.remotecontrol.socket;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import zho.remotecontrol.gson.ElecApp;
import zho.remotecontrol.text.Main;

/**
 * Created by zhodui on 2018/10/23.
 */

//socket实现发送数据和接收服务器的数据
public class SocketClient implements  Runnable{


    public static final int SOCKET_NOTCONNECT = -1;
    public static final int SOCKET_ON = 1;
    public static final int SOCKET_OFF = 0;
    public static final int SOCKET_ADD = 2;
    public static final int SOCKET_DELETE = 3;
    public static final int SOCKET_CHECK = 4;
    public static final int SOCKET_CONNTENTC =  5;
    public static final int SOCKET_BUTTON_STATUS = 6;
    public int socket_mode ;

    public static  Socket socket;
    private static  BufferedReader bufferedReader;
    private static PrintWriter printWriter;
    private Handler handler;
    private static PrintStream out = null;

    public SocketClient(String host,int port)throws  UnknownHostException,IOException,SocketTimeoutException{
//        socket = new Socket(host,port);
        //读取数据超时
//        socket.setSoTimeout(3000);
//        //连接超时
//        SocketAddress socketAddress = new InetSocketAddress(host,port);
//        socket.connect(socketAddress,3000);
//        try{
            socket = new Socket();
            socket.connect(new InetSocketAddress(host, port), 6000);//设置连接请求超时时间10 s
//            socket.setSoTimeout(3000);//设置读操作超时时间30 s
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printWriter = new PrintWriter(socket.getOutputStream());
            out = new PrintStream(socket.getOutputStream());
            socket_mode = SOCKET_CONNTENTC;

//        } catch (IOException e){
//            e.printStackTrace();
//        }

    }
    public SocketClient(){

    }

    //发送数据
    public void sendMessage(String str){

            printWriter.print(str);
            printWriter.flush();

//        out.print(str);
//        out.flush();
    }

    public boolean isConnected  (){
        if(socket != null &&!socket.isClosed())
            return socket.isConnected();
        return false;
    }

    //获取数据
    public String reciveMessage(){
        char[] buffer = new char[1024];
        int count;
        String str = null;

        String content;
        try{
            while((str = bufferedReader.readLine())!=null){
                return str;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return str;
    }


    private String getInfo() {
        int cnt;
        char[] temp = null;
        char []buff=new char[1024];
        try {
            if((cnt=bufferedReader.read(buff))>0)
            {
                temp = new char[cnt];

                for (int i = 0; i < cnt; i++)
                {
                    temp[i] = buff[i];
                }

            }

            Log.d("getInfo: ",new String(temp));
            String str = new String(temp);
            Log.d("getInfo: ",str);
            return str;

        }
        catch (SocketTimeoutException e){
            e.printStackTrace();
            if (!socket.isClosed() && socket.isConnected()) {
                Log.i("xfh", "读取网关数据超时!");
                socket_mode = SOCKET_NOTCONNECT;
                close();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean isEmpty(){
        return socket == null;
    }

    public void close(){
        if(socket != null){
            try{
                socket_mode = SOCKET_NOTCONNECT;
                socket.close();
                printWriter.close();
                bufferedReader.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


    public void setHandler(Handler handler) {
        this.handler = handler;
    }
    @Override
    public void run() {
        try{
            while(socket_mode != SOCKET_NOTCONNECT) {
                String receice = getInfo();

                Message message = new Message();
                //String receice = reciveMessage();
                if (receice != null) {
                    //用于判断是否用户登陆成功
                    if (receice.equals("success")) {
                        message.what = SOCKET_CONNTENTC;
                        Log.d("run: ","Socket_conntect");
                    } else {
//                        JSONObject packetObject = new JSONObject(receice);
//                        JSONObject contentObject = packetObject.getJSONObject("result");
//                        if (contentObject != null) {
//                            message.what = SOCKET_BUTTON_STATUS;
//                        }
                        message.what = SOCKET_CHECK;
                    }
                    message.obj = new String(receice);
                    handler.sendMessage(message);
                }
            }
            //通知主线程socket已断开
            if(socket_mode ==  SOCKET_NOTCONNECT){
                Message meg = new Message();
                meg.what = SOCKET_NOTCONNECT;
                handler.sendMessage(meg);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        try{
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
